package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.Tess4jClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;

    /**
     * 自动审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        //文章存在,如果提交,则进行审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //审核内容中的文字和图片
            //提取文本和图片
            Map<String, Object> map = handleTextAndImages(wmNews);
            //审核文本内容
            String content = (String) map.get("content");
            //审核自管理敏感词
            boolean scan = handleSensitiveScan(content, wmNews);
            if (!scan) return;
            //阿里云审核文本
//            boolean textScan = handleTextScan(content, wmNews);
//            if (!textScan) return;
            //审核图片
            List<String> images = (List<String>) map.get("images");

            boolean imageScan = handleImageScan(images, wmNews);
            if (!imageScan) return;
            //审核完成,保存APP端的相关数据
            ResponseResult result = saveAppArticle(wmNews);
            if (!result.getCode().equals(200)) {
                throw new RuntimeException("文章审核,保存app端相关数据失败");
            }
            //在news中回填article_id
            Long articleId = (long) result.getData();
            wmNews.setArticleId(articleId);
            updateWmNwes(wmNews, (short) 9, "审核成功");
        }
    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理敏感词
     *
     * @param content
     * @param wmNews
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        //获取数据库中自定义的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);
        //查看文章中是否包含敏感词.
        Map<String, Integer> res = SensitiveWordUtil.matchWords(content);
        if (res.size() > 0) {
            //存在敏感词
            updateWmNwes(wmNews, (short) 2, "文章存在自定义敏感词" + res);
            flag = false;
        }
        return flag;
    }


    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmChannelService wmChannelService;

    /**
     * 审核完成,保存文章到app端
     *
     * @param wmNews
     */
    public ResponseResult saveAppArticle(WmNews wmNews) {
        //通过feign接口调用client存储article
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //属性不一致的手动设置
        //作者
        Long userId = wmNews.getUserId().longValue();
        dto.setAuthorId(userId);
//        WmUser user = wmUserService.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getId, userId));
        WmUser user = wmUserService.getById(userId);
        if (user != null) {
            dto.setAuthorName(user.getName());
        }
        //布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel channel = wmChannelService.getById(wmNews.getChannelId());
        dto.setChannelName(channel.getName());
        //保存文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());
        ResponseResult responseResult = iArticleClient.save(dto);
        return responseResult;
    }

    /**
     * 审核纯文本内容
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        if ((wmNews.getTitle() + "" + wmNews.getContent()).length() == 0) {
            return flag;
        }
        //文本审核
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map != null) {
                if (map.get("suggestion").equals("bolck")) {
                    //存在敏感词,审核失败
                    flag = false;
                    //更新文章信息
                    updateWmNwes(wmNews, (short) 2, "存在敏感词,审核失败");
                }
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNwes(wmNews, (short) 3, "存在不确定信息,需要人工审核");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 审核不通过,修改数据库文章信息
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNwes(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核图片内容
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (images == null || images.size() == 0) {
            return flag;
        }
        List<byte[]> imageList = new ArrayList<>();
        //从minio下载图片,去重
        try {
            images = images.stream().distinct().collect(Collectors.toList());
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //图片OCR识别;从byte转换为BufferedImage
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(bis);
                //识别文字,获取结果
                String res = tess4jClient.doOcr(imageFile);
                boolean textScan = handleSensitiveScan(res, wmNews);
                if (!textScan) flag = false;
                imageList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
/*        //审核图片
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map != null) {
                //审核失败
                if (map != null) {
                    if (map.get("suggestion").equals("bolck")) {
                        //存在敏感词,审核失败
                        flag = false;
                        //更新文章信息
                        updateWmNwes(wmNews, (short) 2, "存在敏感词,审核失败");
                    }
                    if (map.get("suggestion").equals("review")) {
                        flag = false;
                        updateWmNwes(wmNews, (short) 3, "存在不确定信息,需要人工审核");
                    }
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }*/
        return flag;
    }


    /**
     * 提取内容文字及图片,封面图片
     *
     * @param wmNews
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        StringBuilder stringBuilder = new StringBuilder();
        List<String> imageList = new ArrayList<>();
        //封面图片 逗号分割的多个字符串
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] images = wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(images));
        }
        //内容文字
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> list = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : list) {
                if (map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")) {
                    imageList.add(map.get("value").toString());
                }
            }
        }
        //返回提取的文字及图片内容
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", stringBuilder.toString());
        resultMap.put("images", imageList);
        return resultMap;
    }
}
